package com.ionehe.group.common.uaa.ex.dto;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ionehe.group.common.uaa.ex.enums.UserStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/11/25
 * Time: 10:29 下午
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 *
 * SpringSecurity需要的用户详情
 */
public class CommonUserDetails implements UserDetails {
    private LoginInfoDTO loginInfoDTO;
    private List<FunctionDTO> functionDTOList;
    public CommonUserDetails(LoginInfoDTO loginInfoDTO, List<FunctionDTO> functionDTOList) {
        this.loginInfoDTO = loginInfoDTO;
        this.functionDTOList = functionDTOList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的角色
        if (CollUtil.isEmpty(functionDTOList)) {
            return null;
        }
        functionDTOList = functionDTOList.stream().filter(fun -> StrUtil.isNotBlank(fun.getUrl())).collect(Collectors.toList());

        return functionDTOList.stream()
                .map(fun ->new SimpleGrantedAuthority(fun.getUrl()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return loginInfoDTO.getPassword();
    }

    @Override
    public String getUsername() {
        return loginInfoDTO.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if (Objects.equals(loginInfoDTO.getStatus(), UserStatus.FREEZE.getValue())) {
            return false;
        }
        return true;
    }
}
